//
//  JJAlbumListModel+internal.swift
//  JJAlbum
//
//  Created by 吴梓杭 on 2025/10/11.
//

import UIKit
import Photos

public extension JJAlbumListModel {
    
    @discardableResult
    func internal_preloadPhotos(_ loadAll: Bool = false) -> [JJAssetModel] {
        // 受限访问时，如果首次未选择任何照片，currentLoadIndex会为0，那么后续再添加照片的时候，需要重置该值来触发重新加载
        // bug: https://github.com/longitachi/ZLPhotoBrowser/issues/1016
        if currentLoadIndex == 0, models.count != result.count {
            currentLoadIndex = result.count
            models.removeAll()
        }
        
        guard currentLoadIndex > 0 else { return [] }
        
        let tool = JJCommonTools()
        var loadCount = tool.onceLoadCount
        let isFirstLoad = currentLoadIndex == result.count
        if isFirstLoad {
            // mod横竖屏列数的最小公倍数，并在第一次加载时候把余数给加载了，从而使后续分页加载的数据均为整数行
            let mod = result.count % tool.lcmColumns
            loadCount = tool.onceLoadCount + mod
        }
        
        let minIndex = loadAll ? 0 : max(0, currentLoadIndex - loadCount)
        let indexSet = IndexSet(minIndex..<currentLoadIndex)
        currentLoadIndex = minIndex
        let models = JJPhotoManager.fetchPhoto(
            in: result,
            ascending: true,
            allowSelectImage: true,
            allowSelectVideo: true,
            indexSet: indexSet
        )
        
        self.models.insert(contentsOf: models, at: 0)
        
        return models
    }
    
    func refreshResult() {
        result = PHAsset.fetchAssets(in: collection, options: option)
    }
    
    override func isEqual(_ object: Any?) -> Bool {
        guard let object = object as? JJAlbumListModel else {
            return false
        }
        
        return title == object.title &&
            count == object.count &&
            headImageAsset?.localIdentifier == object.headImageAsset?.localIdentifier
    }
}
